<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use App\Models\GoodsCategory;
use App\Models\Goods;
use App\Models\GoodsType;
use App\Models\Spec;
use App\Models\SpecItem;
use App\Models\SpecGoodsPrice;
class GoodsController extends Controller
{
    /*
	 * 商品管理
	 * 
	 * */
	protected function index(){
		$goods_list = Goods::paginate(15);
		return view('admin.goods.index',[
			'goods_list'	=> $goods_list
			]);		
	}
	
	
	/*
	 * 商品添加
	 * 
	 * */
	protected function add(Request $request){

		if($request->isMethod('post')){
			$input = $request->only('cat_id','spec_type','goods_name','shop_price','cost_price','sort','original_img','is_on_sale','goods_content','item');

	        $validator = \Validator::make($input, [
	            'cat_id' => 'required',
	            'goods_name' => 'required',
	            'shop_price' => 'required',
	        ]);			
	        if ($validator->fails()) {
	            $msg = $validator->errors()->first();
				return response()->json([
					'code'	=> '10001',
					'msg'	=> $msg,
					'url'	=> ''
					]);						
				
	        }
			$goods = new Goods;
			$goods->cat_id			= $input['cat_id'];
			$goods->goods_name		= $input['goods_name'];
			$goods->shop_price		= $input['shop_price'];
			$goods->cost_price		= $request->has('cost_price') ? $input['cost_price'] : 0;
			$goods->sort			= $input['sort'];
			$goods->original_img	= $input['original_img'];
			$goods->is_on_sale		= $input['is_on_sale'];
			$goods->goods_content	= $input['goods_content'];
			$goods->spec_type		= $input['spec_type'];
			if($goods->save()){
				if($request->has('item')){
					$this->goodsSpecAdd($goods->goods_id,$input['item']);
				}
	
				return response()->json([
					'code'	=> '00000',
					'msg'	=> '商品添加成功！',
					'url'	=> route('admin.goods.index')
					]);
			}else{
				return response()->json([
					'code'	=> '10001',
					'msg'	=> '商品添加失败！',
					'url'	=> ''
					]);				
			}

		}
		$goodstype_list = GoodsType::select('id','name')->get();
		$cate_res = GoodsCategory::select('id','name','pid','sort')->get();
		$cate_list = array2level($cate_res);
		return view('admin.goods.add',[
			'cate_list'		=> $cate_list,
			'goods_type_list'	=> $goodstype_list
			]);
	}


	/*
	 * 添加商品规格
	 * */
	protected function goodsSpecAdd($goods_id,$item){
		foreach ($item as $k => $v) {
			$specgoodsprice = new SpecGoodsPrice;
			$specgoodsprice->goods_id	= $goods_id;
			$specgoodsprice->key		 = $k;
			$specgoodsprice->key_name	 = $v['key_name'];
			$specgoodsprice->price		 = $v['price'];
			$specgoodsprice->store_count = $v['store_count'];
			$specgoodsprice->save();			
		}
	}

	/*
	 * 编辑
	 * */
	protected function edit(Request $request,$id=0){
		if($request->isMethod('post')){
			$input = $request->only('goods_id','cat_id','spec_type','goods_name','shop_price','cost_price','sort','original_img','is_on_sale','goods_content','item');
			$goods = Goods::find($input['goods_id']);
			$goods->cat_id			= $input['cat_id'];
			$goods->goods_name		= $input['goods_name'];
			$goods->shop_price		= $input['shop_price'];
			$goods->cost_price		= $input['cost_price'];
			$goods->sort			= $input['sort'];
			$goods->original_img	= $input['original_img'];
			$goods->is_on_sale		= $input['is_on_sale'];
			$goods->goods_content	= $input['goods_content'];
			$goods->spec_type		= $input['spec_type'];
			if($goods->save()){
				if($request->has('item')){
					SpecGoodsPrice::where('goods_id',$goods->goods_id)->delete();
					$this->goodsSpecAdd($goods->goods_id,$input['item']);
				}				
				return response()->json([
					'code'	=> '00001',
					'msg'	=> '保存成功！',
					'url'	=> ''
					]);					
			}else{
				return response()->json([
					'code'	=> '10001',
					'msg'	=> '保存失败！',
					'url'	=> ''
					]);					
			}
		}
		
		
		$goodstype_list = GoodsType::select('id','name')->get();
		$cate_res = GoodsCategory::select('id','name','pid','sort')->get();
		$cate_list = array2level($cate_res);
		$goods = Goods::find($id);
		return view('admin.goods.edit',[
			'goods'	=> $goods,
			'cate_list'	=> $cate_list,
			'goods_type_list'	=> $goodstype_list
			]);
		
	}
	
	/*
	 * 删除
	 * 
	 * */
	protected function del($id){
		$goods = Goods::find($id);
		if($goods->delete()){
			SpecGoodsPrice::where('goods_id',$id)->delete();
			return response()->json([
				'code'	=> '00001',
				'msg'	=> '删除成功！',
				'url'	=> ''
				]);				
		}else{
			return response()->json([
				'code'	=> '10001',
				'msg'	=> '删除失败！',
				'url'	=> ''
				]);			
		}
	}	

	/*
	 * 上下架
	 * 
	 * */
	protected function onSale(Request $request){
		$goods_id 	= $request->input('goods_id');
		$is_on_sale = $request->input('is_on_sale');
		$goods = Goods::find($goods_id);
		$goods->is_on_sale = $is_on_sale;
		if($goods->save()){
				return response()->json([
					'code'	=> '00000',
					'msg'	=> '设置成功！',
					'url'	=> route('admin.goods.index')
					]);			
		}else{
				return response()->json([
					'code'	=> '10001',
					'msg'	=> '设置失败！',
					'url'	=> ''
					]);
		}
		
	}
	
	
	/*
	 * 输出规格模板
	 * 
	 * */
	protected function getSpecTpl(Request $request){
		$type_id = $request->input('type_id');
		$goods_id = $request->has('goods_id') ? $request->input('goods_id') : 0;
		$spec_list = Spec::where('type_id',$type_id)->select('id','type_id','name')->get();
		$i=0;
		foreach ($spec_list as $spec) {
			$spec_list[$i]['item'] = $spec->item()->select('id','item')->get();//获取规格项
			$i++;
		}
		$items_ids = array();
		if($goods_id){
			$items_id = SpecGoodsPrice::where('goods_id',$goods_id)->selectRaw("GROUP_CONCAT(`key` SEPARATOR '_') AS items_id")->first()['items_id'];
			$items_ids = explode('_', $items_id);			
		}
//		dd($spec->specitem);
		return view('admin.goods.getspectpl',array(
			'list'	=> $spec_list,
			'items_ids'	=> $items_ids
			));
		
	}
	
	/*
	 * 
	 * 输出input
	 * 
	 * */
	protected function getSpecInput(Request $request){
		if(!$request->has('spec_arr')){
			return '';
		}
		if($request->has('goods_id')){
			$goods_id = $request->input('goods_id');
		}else{
			$goods_id = 0;
		}
		$spec_arr = $request->input('spec_arr');
		$str = $this->getSpecInputa($goods_id,$spec_arr);
		echo $str;
		
		
	}
	
	/*
	 * 返回表格字符串
	 * */
	private function getSpecInputa($goods_id,$spec_arr){
        // 排序
        foreach ($spec_arr as $k => $v){
            $spec_arr_sort[$k] = count($v);
        }
        asort($spec_arr_sort);        
        foreach ($spec_arr_sort as $key =>$val){
            $spec_arr2[$key] = $spec_arr[$key];
        }
		$clo_name = array_keys($spec_arr2);  
		$spec_arr2 = combineDika($spec_arr2); //  获取 规格的 笛卡尔积  
     	
     	$spec = $this->convert_arr_key1(Spec::get(['id','name'])->toArray());// 规格表
		$specItem = $this->convert_arr_key(SpecItem::select('id','item','spec_id')->get()->toArray(), 'id');//规格项
		$prices = array();
		if($goods_id){
			$keySpecGoodsPrice = SpecGoodsPrice::where('goods_id',$goods_id)->select('key','key_name','price','store_count','bar_code')->get();//规格项
			foreach ($keySpecGoodsPrice as $v) {
				$prices[$v->key]['price'] = $v->price; 
				$prices[$v->key]['store_count'] = $v->store_count;
			}			
		}
		$str = "<table class='table table-bordered' id='spec_input_tab'>";
		$str .="<tr>";
		
       // 显示第一行的数据
		foreach ($clo_name as $k => $v) {
		    $str .=" <td><b>{$spec[$v]}</b></td>";
		}    
        $str .="<td><b>价格</b></td>
               <td><b>库存</b></td>
             </tr>";
			 
       // 显示第二行开始 
       foreach ($spec_arr2 as $k => $v){
            $str .="<tr>";
            $item_key_name = array();
            foreach($v as $k2 => $v2)
            {
                $str .="<td>{$specItem[$v2]['item']}</td>";
                $item_key_name[$v2] = $spec[$specItem[$v2]['spec_id']].':'.$specItem[$v2]['item'];
            }   
            ksort($item_key_name);            
            $item_key = implode('_', array_keys($item_key_name));
            $item_name = implode(' ', $item_key_name);

			$price = isset($prices[$item_key]['price']) ? $prices[$item_key]['price'] : 0; // 价格默认为0
			$store_count = isset($prices[$item_key]['store_count']) ? $prices[$item_key]['store_count'] : 0; // //库存默认为0
			
            $str .="<td><input name='item[$item_key][price]' value='{$price}' /><input type='hidden' name='item[$item_key][key_name]' value='$item_name' /></td>";
            $str .="<td><input name='item[$item_key][store_count]' value='{$store_count}' /></td>";
            $str .="</tr>";           
       }
        $str .= "</table>";
       return $str;            
		
	}
			
	/*
	 * 将数据库中查出的列表以指定的 id 作为数组的键名
	 * */		
	private function convert_arr_key($arr,$key_name){
	    $result = array();
	    foreach($arr as $key => $val){
	        $result[$val[$key_name]] = $val;
	    }
	    return $result;	
	}
	private function convert_arr_key1($arr){
	    $result = array();
	    foreach($arr as $key => $val){
	        $result[$val['id']] = $val['name'];
	    }
	    return $result;	
	}	


	
}
